<?php
/**
 * Created by dh2y.
 * Blog: http://blog.csdn.net/sinat_22878395
 * Date: 2020/2/6 10:35
 * For:
 */

namespace app\admin\service;


use app\admin\validate\AuthRule;
use app\admin\model\AuthRule as AuthRuleModel;
use app\traits\Result;
use auth\Auth;
use think\exception\ValidateException;

class AuthRuleService
{
    use Result;

    /**
     * 添加/编辑权限
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeRule($data,$scene='add'){
        $data['state'] = isset( $data['state'])? $data['state']:0;
        try {
            validate(AuthRule::class)->scene($scene)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg =Result::error($e->getError(),null, ['token'=>request()->buildToken()]);
            return $msg;
        }


        $model = new AuthRuleModel();
        if ($scene !='add') {
            $result = $model->exists(true)->update($data);
            if ($result) {
                return Result::success('编辑成功');
            } else {
                return Result::error('编辑失败');
            }
        } else {
            $result = $model->create($data);
            if ($result) {
                return Result::success('添加成功');
            } else {
                return Result::error('添加失败');
            }
        }
    }

    /**
     * 获得所有菜单选择数据
     * @return array
     */
    public static function allMenu(){
        $allMenu = AuthRuleModel::where('menu',1)->where('state',1)->field('id,title,pid as parentId')->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();
        return $allMenu;
    }


    /**
     * 权限列表
     * @param bool $check
     * @return array
     */
    public static  function access($check = true){
        $tree = AuthRuleModel::where('state',1)->field('id,title,pid as parentId')->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();

        //是否有复选框
        if ($check){
            foreach ($tree as &$item){
                $item['checkArr'] = '0';
            }
        }

        return $tree;
    }

    /**
     * 权限菜单
     * @param $uid
     * @param bool $level 是否显示1级头部菜单
     * @return array
     */
    public static function authMenu($uid,$level=false){
        //读取用户所属用户组
        $groups = Auth::instance()->getGroups($uid);
        $ids = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);

        $model = AuthRuleModel::field('id,pid as parentId,name,title,menu_icon')
            ->where('state',1)
            ->where('menu',1)
            ->where('id','in',$ids);
        if ($level){
            $lists = $model->where('pid',0)->order(['sort'=>'asc','id'=>'asc'])->select();
        }else{
            $lists = $model->order(['sort'=>'asc','id'=>'asc'])->select();
        }
        return $lists;
    }
}